package com.pithypan.controller;


import com.pithypan.common.Constants;
import com.pithypan.common.FileCategoryEnums;
import com.pithypan.common.FileDelFlagEnums;
import com.pithypan.common.FileFolderTypeEnums;
import com.pithypan.common.utils.R;
import com.pithypan.common.utils.StringTools;
import com.pithypan.convert.FileInfoConvert;
import com.pithypan.dto.SessionWebUserDto;
import com.pithypan.dto.UploadResultDto;
import com.pithypan.entity.FileInfo;
import com.pithypan.entity.UserInfo;
import com.pithypan.service.FileInfoService;
import com.pithypan.vo.FileInfoQuery;
import com.pithypan.vo.FileInfoVo;
import com.pithypan.vo.PaginationResultVo;
import javafx.scene.control.Pagination;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * <p>
 * 文件信息 前端控制器
 * </p>
 *
 * @author author
 * @since 2023-11-23
 */
@RestController
@RequestMapping("/file")
public class FileInfoController extends CommonFileController {

    @Resource
    private FileInfoService fileInfoService;


    /**
     * 文件列表分页查询
     * @param session
     * @param query
     * @param category  类型
     * @return
     */
    @RequestMapping("/loadDataList")
    public R loadDataList(HttpSession session, @RequestBody FileInfoQuery query, String category) {
        FileCategoryEnums categoryEnum = FileCategoryEnums.getByCode(category);
        if (categoryEnum != null) {
            query.setFileCategory(categoryEnum.getCategory()); //文件分类：1:视频 2:音频 3:图片 4:文档 5:其它
        }

        //从session中获取登陆用户信息
        SessionWebUserDto sessionWebUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);

        if (StringTools.isEmpty(query.getFileNameFuzzy())) {
            query.setFileNameFuzzy(null);
        }
        query.setUserId(sessionWebUserDto.getUserId());  //设置用户id
        query.setOrderBy("last_update_time desc");       //根据更新时间降序排序
        query.setDelFlag(2);                             //0:删除 1:回收站 2:正常
        PaginationResultVo result = fileInfoService.findListByPage(query);
        return R.ok().data("dataList", result);
    }


    /**
     * 上传文件分片
     * @param session
     * @param fileId      文件id
     * @param file        文件的分片
     * @param fileName    文件名
     * @param filePid     文件父级目录id
     * @param fileMd5     文件Md5值
     * @param chunkIndex  当前上传的是第几分片
     * @param chunks      文件总分片
     * @return
     */
    @RequestMapping("/uploadFile")
    public R uploadFile(HttpSession session, String fileId, MultipartFile file,
                        String fileName, String filePid, String fileMd5, Integer chunkIndex, Integer chunks) {
        //从session中获取登陆用户信息
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        UploadResultDto resultDto = fileInfoService.uploadFile(webUserDto, fileId, file, fileName, filePid,
                fileMd5, chunkIndex, chunks);
        return R.ok().data("resultDto", resultDto);
    }


    /**
     * 请求图片封面
     * @param response
     * @param imageFolder   预览图路径
     * @param imageName     预览图文件名
     */
    @RequestMapping("/getImage/{imageFolder}/{imageName}")
    public void getImage(HttpServletResponse response, @PathVariable("imageFolder") String imageFolder, @PathVariable("imageName") String imageName) {
        super.getImage(response, imageFolder, imageName);
    }


    /**
     * 视频文件分段预览
     * @param response
     * @param fileId   视频文件id 或 视频分片名称（如：QZeD5BDF9w_0000.ts）
     */
    @RequestMapping("/ts/getVideoInfo/{fileId}")
    public void getVideo(HttpServletResponse response, HttpSession session, @PathVariable("fileId") String fileId) {
        //从session中获取登陆用户信息
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        super.getFile(response, fileId, webUserDto.getUserId());
    }


    /**
     * 其它文件 预览
     * @param response
     * @param session
     * @param fileId
     */
    @RequestMapping("/getFile/{fileId}")
    public void getFile(HttpServletResponse response, HttpSession session, @PathVariable("fileId") String fileId) {
        //从session中获取登陆用户信息
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        super.getFile(response, fileId, webUserDto.getUserId());
    }


    /**
     * 新建目录
     * @param session
     * @param filePid      目录的父级id
     * @param fileName     目录名称
     * @return
     */
    @RequestMapping("/newFoloder")
    public R newFoloder(HttpSession session, String filePid, String fileName) {
        //从session中获取登陆用户信息
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        FileInfo fileInfo = fileInfoService.newFoloder(webUserDto.getUserId(), filePid, fileName);
        return R.ok().data("fileData", FileInfoConvert.INSTANCE.entity2vo(fileInfo));
    }


    /**
     * 根据 id串 获取相对应的目录
     * @param session
     * @param path       路径, id串用 / 字符分隔（例：wuvakndsa/aknababa）
     * @return
     */
    @RequestMapping("/getFolderInfo")
    public R getFolderInfo(HttpSession session, @RequestParam String path) {
        //从session中获取登陆用户信息
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        return super.getFolderInfo(webUserDto.getUserId(), path);
    }


    /**
     * 修改文件名称
     * @param fileId
     * @param fileName
     * @return
     */
    @RequestMapping("/rename")
    public R rename(HttpSession session, String fileId, String fileName) {
        //从session中获取登陆用户信息
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        FileInfo fileInfo = fileInfoService.rename(webUserDto.getUserId(), fileId, fileName);
        return R.ok().data("fileData", FileInfoConvert.INSTANCE.entity2vo(fileInfo));
    }


    /**
     * 获取指定目录下的所有目录
     * @param session
     * @param filePid
     * @param currentFileIds  需要排除返回的文件id，以 , 字符分隔
     * @return
     */
    @RequestMapping("/loadAllFolder")
    public R loadAllFolder(HttpSession session, String filePid, String currentFileIds) {
        //从session中获取登陆用户信息
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        FileInfoQuery infoQuery = new FileInfoQuery();
        infoQuery.setUserId(webUserDto.getUserId());
        infoQuery.setFilePid(filePid);
        infoQuery.setFolderType(FileFolderTypeEnums.FOLDER.getType());
        if (!StringTools.isEmpty(currentFileIds)) {
            infoQuery.setExcludeFileIdArray(currentFileIds.split(","));
        }
        infoQuery.setDelFlag(FileDelFlagEnums.USING.getFlag());
        infoQuery.setOrderBy("create_time desc");
        List<FileInfo> list = fileInfoService.findListByParam(infoQuery);
        return R.ok().data("fileInfoList", FileInfoConvert.INSTANCE.listentity2vo(list));
    }


    /**
     * 移动文件
     * @param session
     * @param fileIds   需要移动的文件id, 以 , 字符分隔
     * @param filePid   移动目的地
     * @return
     */
    @RequestMapping("/changeFileFolder")
    public R changeFileFolder(HttpSession session, String fileIds, String filePid) {
        //从session中获取登陆用户信息
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        fileInfoService.changeFileFolder(webUserDto.getUserId(), fileIds, filePid);
        return R.ok();
    }


    /**
     * 创建下载
     * @param session
     * @param fileId 需下载的文件
     * @return
     */
    @RequestMapping("/createDownloadUrl/{fileId}")
    public R createDownloadUrl(HttpSession session, @PathVariable("fileId") String fileId) {
        //从session中获取登陆用户信息
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        return super.createDownloadUrl(webUserDto.getUserId(), fileId);
    }


    /**
     * 文件下载
     * @param request
     * @param response
     * @param code
     * @throws Exception
     */
    @RequestMapping("/download/{code}")
    public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable("code") String code) throws Exception {
        super.download(request, response, code);
    }


    /**
     * 删除文件,修改delFlag
     * @param session
     * @param fileIds
     * @return
     */
    @RequestMapping("/delFile")
    public R delFile(HttpSession session, String fileIds) {
        //从session中获取登陆用户信息
        SessionWebUserDto webUserDto = (SessionWebUserDto) session.getAttribute(Constants.SESSION_KEY);
        fileInfoService.removeFile2RecycleBatch(webUserDto.getUserId(), fileIds);
        return R.ok();
    }
}
